#include "ComboBoxItemDelegate.hxx"

#include "ComboBoxItemDelegate.hxx"
#include <QComboBox>
#include <QSettings>

#include "Project.hxx"


ComboBoxItemDelegate::ComboBoxItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
    _project = nullptr;
}


ComboBoxItemDelegate::~ComboBoxItemDelegate()
{
}


QWidget *ComboBoxItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // Create the combobox and populate it
    QComboBox *cb = new QComboBox(parent);
    const int row = index.row();

    QVariant val = index.data(Qt::UserRole);
    int classIndex = val.value<int>();

    if (_project)
    {
        std::vector<Class*>* classes = _project->getClasses();
        for (int i = 0; i < classes->size(); i++)
        {
            Class* cls = classes->at(i);
            QVariant data;
            data.setValue(cls);

            cb->addItem(cls->getName().c_str(),data);

            if (cls->getId() == classIndex)
                cb->setCurrentIndex(i);

        }
    }

    return cb;
}


void ComboBoxItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *cb = qobject_cast<QComboBox *>(editor);
    Q_ASSERT(cb);
    // get the index of the text in the combobox that matches the current value of the item
    const QString currentText = index.data(Qt::EditRole).toString();

    const int cbIndex = cb->findText(currentText);
    // if it is valid, adjust the combobox
    if (cbIndex >= 0)
       cb->setCurrentIndex(cbIndex);
}


void ComboBoxItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *cb = qobject_cast<QComboBox *>(editor);
    Q_ASSERT(cb);

    
    model->setData(index, cb->currentText(), Qt::EditRole);

    QVariant itemData = cb->currentData();
    Class* cls = itemData.value<Class*>();

    QVariant val;
    val.setValue<int>(cls->getId());

    model->setData(index, val, Qt::UserRole);
}
